package com.fyzk.activity.chongzhi.epay;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import org.json.JSONArray;
import org.json.JSONObject;

public class PayUtil {

    private static PayUtil payUtil;

    private Handler handler;

    private static final String lock = "lock";

    private volatile LoadDialog mDialog;

    private PayBean payBean;

    private String callBackUrl = "";

    public static PayUtil getInstance() {
        if (payUtil == null) {
            synchronized (lock) {
                if (payUtil == null) {
                    payUtil = new PayUtil();
                }
            }
        }
        return payUtil;
    }

    private PayUtil() {
    }

    /**
     * 注册handle监听 监听是唯一的
     *
     * @param mHandler
     */
    public void registerHandleCallback(Handler mHandler) {
        handler = mHandler;
    }

    /**
     * 移除handle监听
     */
    public void removeHandleCallback() {
        handler = null;
    }

    /**
     * 人民币加密调用
     *
     * @param payBean
     */
    public void payOnline(PayBean payBean, Activity context) {

        this.payBean = payBean;
        if (mDialog == null) {
            mDialog = new LoadDialog(context);
            if (payBean == null || payBean.callbackUrl == null || "".equals(payBean.callbackUrl)) {
                ResponseMessage.sendExceptionMessage(ResponseMessage.REQUEST, handler);
                mDialog = null;
                return;
            }
            if (!mDialog.isShowing()) {
                callBackUrl = payBean.callbackUrl;
                try {
                    String params = makeOnlineJsonParams(payBean);
                    new ServiceAysnTask(context).execute(Config.pay_online_server_url, params);
                } catch (Exception ex) {
                    ResponseMessage.sendExceptionMessage(ResponseMessage.REQUEST, handler);
                    mDialog = null;
                }
            }
        }
    }

    /**
     * 制作人民币 json参数
     *
     * @return
     */
    private String makeOnlineJsonParams(PayBean payBean) throws Exception {
        JSONObject jsonObject = new JSONObject();
        setJosnData(jsonObject, "merchantId", payBean.merchantId);
        setJosnData(jsonObject, "requestId", payBean.requestId);
        setJosnData(jsonObject, "orderAmount", payBean.orderAmount);
        setJosnData(jsonObject, "orderCurrency", payBean.orderCurrency);
        setJosnData(jsonObject, "notifyUrl", payBean.notifyUrl);
        setJosnData(jsonObject, "callbackUrl", payBean.callbackUrl);
        setJosnData(jsonObject, "remark", payBean.remark);

        setJosnData(jsonObject, "cashierVersion", payBean.cashierVersion);
        setJosnData(jsonObject, "forUse", payBean.forUse);
        setJosnData(jsonObject, "payerName", payBean.payerName);
        setJosnData(jsonObject, "phoneNum", payBean.phoneNum);
        setJosnData(jsonObject, "idType", payBean.idType);
        setJosnData(jsonObject, "idNum", payBean.idNo);
        setJosnData(jsonObject, "bankCardNum", payBean.cardNo);
        setJosnData(jsonObject, "email", payBean.email);
        setJosnData(jsonObject, "paymentModeCode", payBean.paymentModeCode);
        setJosnData(jsonObject, "merchantUserId", payBean.merchantUserId);
        setJosnData(jsonObject, "bindCardId", payBean.bindCardId);

        JSONArray jsonArray = new JSONArray();
        for (ProductBean productBean : payBean.productBeans) {
            JSONObject object = new JSONObject();
            setJosnData(object, "name", productBean.content_name);
            setJosnData(object, "quantity", productBean.content_quantity);
            setJosnData(object, "amount", productBean.content_amount);
            setJosnData(object, "receiver", productBean.content_receiver);
            setJosnData(object, "description", productBean.content_description);
            jsonArray.put(object);
        }
        jsonObject.put("contents", jsonArray);

        setJosnData(jsonObject, "cardNo", payBean.cardNo);
        setJosnData(jsonObject, "cvv2", payBean.cvv2);
        setJosnData(jsonObject, "expiryDate", payBean.expiryDate);
        setJosnData(jsonObject, "idNo", payBean.idNo);
        setJosnData(jsonObject, "mobileNo", payBean.mobileNo);
        setJosnData(jsonObject, "name", payBean.name);

        return jsonObject.toString();
    }

    private void setJosnData(JSONObject jsonObject, String key, String str) throws Exception {
        if (str == null) {
            str = "";
        }
        jsonObject.put(key, str);
    }

    /**
     * 与远程服务通信的线程类
     *
     * @author BDK
     * AsyncTask  异步任务
     */
    private class ServiceAysnTask extends AsyncTask<Object, Object, Respose> {

        private Activity context;

        public ServiceAysnTask(Activity context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mDialog != null && !mDialog.isShowing()) {
                mDialog.show();
            }
        }

        @Override
        protected Respose doInBackground(Object... params) {
            return NetUtil.getResponseForPost((String) params[0], (String) params[1]);
        }

        @Override
        protected void onPostExecute(Respose result) {
            super.onPostExecute(result);
            try {
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.cancel();
                }
                mDialog = null;
                dealResult(result, context);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 处理请求结果
     *
     * @param result
     */
    private void dealResult(Respose result, Activity context) {
        if (result == null) {
            ResponseMessage.sendExceptionMessage(ResponseMessage.RESPONSE, handler);
            return;
        }
        try {
            JSONObject jsonObject = new JSONObject(result.resposeString);
            String status = jsonObject.getString("status");
            if (result.statusCode == 200) {
                if (status.equals("SUCCESS")) {
                    String responseData = jsonObject.getString("responseData");
                    if (payBean != null) {
//                        if (payBean.paymentModeCode.equals("APP-ALIPAY-P2P")) {
//                            EhkingPayUtil ehkingPayUtil = EhkingPayUtil.getInstance(context);
//                            ehkingPayUtil.registerHandleCallback(handler);
//                            ehkingPayUtil.alipay(responseData);
//                        } else if (payBean.paymentModeCode.equals("APP-WEIXIN-P2P")) {
//                            EhkingPayUtil ehkingPayUtil = EhkingPayUtil.getInstance(context);
//                            ehkingPayUtil.tenpay(responseData, Config.APPID);
//                        }
                    }
                } else if (status.equals("REDIRECT")) {//调用yhjPayUtil 继续支付调用
//                    String responseData = jsonObject.getString("responseData");
//                    if (null != responseData && !"".equals(responseData)) {
//                        EhkingPayUtil ehkingPayUtil = EhkingPayUtil.getInstance(context);
//                        ehkingPayUtil.registerHandleCallback(handler);
//                        ehkingPayUtil.pay(responseData, callBackUrl);
//                    } else {
//                        ResponseMessage.sendExceptionMessage(ResponseMessage.RESPONSE, handler);
//                    }
                } else {
                    Message msg = Message.obtain();
                    msg.what = ResponseMessage.errorCodes[1];
                    msg.obj = result.resposeString;
                }
            } else {
                Message msg = Message.obtain();
                msg.what = ResponseMessage.errorCodes[1];
                msg.obj = result.resposeString;
            }

        } catch (Exception ex) {
            ResponseMessage.sendExceptionMessage(ResponseMessage.RESPONSE, handler);
        }
    }

    /**
     * 回调
     *
     * @param message
     */
    void sendMessage(Message message) {
        handler.sendMessage(message);
    }
}
